package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportServiceImpl implements ReportService {

    // 注入OrderMapper
    private final OrderMapper orderMapper;
    private final UserMapper userMapper;
    private final WorkspaceService workspaceService;


    // 获取营业额统计
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 创建日期列表
        List<LocalDate> dateList = new ArrayList<>();

        // 将开始日期添加到日期列表中
        dateList.add(begin);

        // 循环遍历日期列表，直到结束日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 创建营业额列表
        List<Double> turnoverList = new ArrayList<>();
        // 遍历日期列表
        for (LocalDate date : dateList) {
            // 获取开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 创建map，用于查询
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            // 查询营业额
            Double turnover = orderMapper.sumByMap(map);
            // 如果营业额为空，则设置为0
            turnover = turnover == null ? 0.0 : turnover;
            // 将营业额添加到营业额列表中
            turnoverList.add(turnover);
        }

        // 返回营业额统计对象
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    // 获取用户统计
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 创建日期列表
        List<LocalDate> dateList = new ArrayList<>();
        // 将开始日期添加到日期列表中
        dateList.add(begin);
        // 循环遍历日期列表，直到结束日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 创建新用户列表和总用户列表
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", endTime);
            Integer totalUser = userMapper.countByMap(map);

            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        // 返回用户统计对象
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }


    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 创建日期列表
        List<LocalDate> dateList = new ArrayList<>();
        // 将开始日期添加到日期列表中
        dateList.add(begin);
        // 循环遍历日期列表，直到结束日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();

        List<Integer> vaildOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount=getOrderCount(beginTime,endTime,null);
            Integer vaildOrdeCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            vaildOrderCountList.add(vaildOrdeCount);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer vaildOrderCount = vaildOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate =0.0;
               if (totalOrderCount != 0) {
                   orderCompletionRate = vaildOrderCount.doubleValue() / totalOrderCount;
               }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(vaildOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(vaildOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.countByMap(map);
    }


    public SalesTop10ReportVO getSalasTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salestop10 = orderMapper.getSalestop10(beginTime, endTime);
        List<String> names = salestop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList=StringUtils.join(names,",");

        List<Integer> numbers = salestop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList=StringUtils.join(numbers,",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }


    public void exportBusinessData(HttpServletResponse response) {
        // 获取当前日期的前30天
        LocalDate dateBegin=LocalDate.now().minusDays(30);
        // 获取当前日期的前一天
        LocalDate dateEnd=LocalDate.now().minusDays(1);

        // 调用workspaceService的getBusinessData方法，获取业务数据
        BusinessDataVO businessDataVo = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN)
                                , LocalDateTime.of(dateEnd, LocalTime.MAX));
        // 获取模板文件
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 创建Excel工作簿
            XSSFWorkbook excel=new XSSFWorkbook(in);
            // 获取第一个工作表
            XSSFSheet sheet=excel.getSheet("Sheet1");

            // 设置报表标题
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);

            // 设置报表数据
            XSSFRow row=sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVo.getTurnover());
            row.getCell(4).setCellValue(businessDataVo.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVo.getNewUsers());


            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVo.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVo.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date =dateBegin.plusDays(i);
                workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVo.getTurnover());
                row.getCell(3).setCellValue(businessDataVo.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVo.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVo.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVo.getNewUsers());

            }

            // 将Excel写入响应流
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
